import router from "./router";
import store from "./store";
import NProgress from "nprogress"; // 进度条
import "nprogress/nprogress.css";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ["/login"]; // no redirect whitelist

router.beforeEach(async(to, from, next) => {
    //?name=aaa&password=bbb
    const { name, password } = to.query;
    // start progress bar
    NProgress.start();
    // set page title
    document.title = to.meta.title ?
        `${to.meta.title}-vue Admin Template` :
        "vue Admin Template";

    const hasName = store.getters.name;

    if (name && password) {
        //如果浏览器地址传递用户名密码直接登录跳转对应页面
        await store.dispatch("user/login", {
            isFlag: true,
            userName: name,
            password: password
        });
        next({ path: "/" });
    }

    if (hasName) {
        if (to.path === "/login") {
            next({ path: "/" });
            NProgress.done();
        } else {
            NProgress.done();
            next();
            // const hasName = store.getters.name;
            // if (hasName == "") {
            //     //用户刷新
            //     store.dispatch("user/GenerateRoutes");
            //     next({ to: to.path });
            //     NProgress.done();
            // } else {
            //     next();
            // }
        }
    } else {
        /* has no login*/
        if (whiteList.indexOf(to.path) !== -1) {
            next();
        } else {
            next("/login");
            NProgress.done();
        }
    }
});

router.afterEach(() => {
    // finish progress bar
    NProgress.done();
});